package com.app.controller;

import com.app.common.SystemConstant;
import com.app.enums.StatusCodeEnum;
import com.app.model.UserModel;
import com.app.service.UserService;
import com.app.util.COSClientUtil;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Random;

@Controller
@RestController
@RequestMapping("/api")
public class UploadController {
    @Autowired
    UserService userService;


    /**
     * 上传文件
     */
    @PostMapping("/upload")
    public Result<?> upload(HttpServletRequest request,
                            @RequestParam("file") MultipartFile file) throws IOException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(StatusCodeEnum.STATUS401.getCode(), StatusCodeEnum.STATUS401.getMsg());
        }
        String mobile = TokenUtils.nothingness(token);
        UserModel user = userService.getUserByOpenid(mobile);
        if (user == null) {
            return Result.error(StatusCodeEnum.STATUS406.getCode(), StatusCodeEnum.STATUS406.getMsg());
        }
        File filePath;
        if (!file.isEmpty()) {
            //上传文件路径
            String path = "";
            path = SystemConstant.DEFAULT_UPLOAD_URL;
            //获得上传文件名
            String fileName = file.getOriginalFilename();
            assert fileName != null;
            int lastIndexOf = fileName.lastIndexOf(".");
            String date = getRandomString2(8);
            //获取文件的后缀名 .jpg
            String suffix = fileName.substring(lastIndexOf);
            filePath = new File(path + File.separator + date + suffix);
            System.out.println(filePath);
            //如果文件目录不存在，创建目录
            if (!filePath.getParentFile().exists()) {
                filePath.getParentFile().mkdirs();
            }
            //将上传文件保存到一个目标文件中
            file.transferTo(filePath);
        } else {
            return Result.error(500, "上传失败");
        }
        //获取COSClient对象
        COSClient cosClient = COSClientUtil.getCosClient();
        // 设置存储桶名称和文件路径
        String bucketName = SystemConstant.bucketName;
        String key = "uploads/" + filePath.getName();
        File localFile = new File(filePath.getPath());
        try {
            // 上传文件到存储桶
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            // 设置存储桶权限
            putObjectRequest.setCannedAcl(CannedAccessControlList.PublicRead);
            cosClient.putObject(putObjectRequest);
            File file1 = new File(filePath.getPath());
            String url = SystemConstant.URL + file1.getName();
            System.out.println("文件上传成功");
            if (file1.delete()) {
                System.out.println(file1.getName() + " 图片已被删除！");
            } else {
                System.out.println("删除图片操作失败！");
            }
            return Result.success(url);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭存储桶客户端
            cosClient.shutdown();
        }
        return Result.success("文件上传失败");
    }

    //删除对象
    @GetMapping("/deleteObject")
    public Result<Object> deleteObject(String filename) {
        //获取COSClient对象
        COSClient cosClient = COSClientUtil.getCosClient();
        // Bucket 的命名格式为 BucketName-APPID ，此处填写的存储桶名称必须为此格式
        String bucketName = SystemConstant.bucketName;
        // 指定被删除的文件在 COS 上的路径，即对象键。例如对象键为 folder/picture.jpg，则表示删除位于 folder 路径下的文件 picture.jpg
        String key = "/uploads/FFuFQ6QV.png";
        cosClient.deleteObject(bucketName, key);
        return Result.success("删除成功");
    }



    //可以指定字符串的某个位置是什么范围的值
    public static String getRandomString2(int length) {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(3);
            long result = 0;
            switch (number) {
                case 0:
                    result = Math.round(Math.random() * 25 + 65);
                    sb.append(String.valueOf((char) result));
                    break;
                case 1:
                    result = Math.round(Math.random() * 25 + 97);
                    sb.append(String.valueOf((char) result));
                    break;
                case 2:
                    sb.append(String.valueOf(new Random().nextInt(10)));
                    break;
            }
        }
        return sb.toString();
    }
}
